package com.yvon.maple.service.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yvon.boot.mybatis.BaseTreeServiceImpl;
import com.yvon.maple.service.system.mapper.DeptMapper;
import com.yvon.maple.service.system.entity.Dept;
import com.yvon.maple.service.system.service.DeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @author : Yvon
 * @since : 2021-11-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl extends BaseTreeServiceImpl<Dept, DeptMapper> implements DeptService {

    @Override
    public boolean save(Dept entity) {
        Dept parentDept = getById(entity.getParentId());
        if (null != parentDept) {
            setTreeProperties(entity, null, OpType.insert);
        }else{
            //新增根节点
            entity.setId(IdWorker.getId());
            entity.setParentIds(entity.getId().toString());
            // 设置当前树全路径排序
            Integer treeSort = entity.getTreeSort();
            String treeSorts = String.format("%06d", treeSort);
            entity.setTreeSorts(treeSorts);
            entity.setTreeLeaf(1);
            // 设置当前节点级别.
            entity.setTreeLevel(1);
        }
        getBaseMapper().insert(entity);

        return Boolean.TRUE;
    }

    @Override
    public boolean updateById(Dept entity) {
        Dept parentDept = getById(entity.getParentId());
        if (null != parentDept) {
            setTreeProperties(entity, parentDept, OpType.update);
            getBaseMapper().updateById(entity);
        }
        return true;
    }

    @Override
    public List<Dept> listDataByLevel(int level, Long parentId) {
        List<Dept> listData = new ArrayList<>();
        level--;
        List<Dept> childrenList = findChildListByParentId(parentId);
        for (Dept dto : childrenList) {
            if (0 == dto.getTreeLeaf() && level != 0) {
                dto.setChildren(this.listDataByLevel(level, dto.getId()));
            } else {
                dto.setChildren(new ArrayList<>());
            }
            listData.add(dto);
        }
        return listData;
    }

    @Override
    public Integer getMaxSort(Long parentId) {
        Integer maxSort = findMaxSort(parentId);
        return maxSort / 10 * 10 + 10;
    }
}
